// 需求：['banner-list', 'banner'] => ['banner-list']
// ['banner-list', 'banner-add', 'banner'] => ['banner-list', 'banner-add', 'banner']

/**
 * routes
 */
const routes = [
  {
    name: "home",
  },
  {
    name: "banner",
    children: [
      {
        name: "banner-list",
      },
      { name: "banner-add" },
    ],
  },
  {
    name: "manager",
    children: [
      {
        name: "manager-list",
      },
    ],
  },
  {
    name: "test",
    children: [{ name: "test-1" }, { name: "test-2" }],
  },
];

const roles = ["banner-list", "banner"];

/**
 * 根据 name 获取 这个 name 在 routes 数组中的 children 字段。
 * @param {*} routes
 * @param {*} name
 */
function getChildrenByName(routes, name) {
  let result = [];
  // routes.forEach((route) => {
  //   if (route.name === name) {
  //     result = route.children ? route.children.map((a) => a.name) : [];
  //   } else if (route.children) {
  //     result = getChildrenByName(route.children, name);
  //   }
  // });
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route.name === name) {
      result = route.children ? route.children.map((a) => a.name) : [];
      break;
    }

    if (route.children) {
      result = getChildrenByName(route.children, name);
    }
  }
  return result;
}

// const result1 = getChildrenByName(routes, "banner");
// console.log(result1);

/**
 * 判断 arr1 中所有项是否在 arr2 中都存在
 */
function isIncludes(arr1, arr2) {
  return arr1.every((item) => {
    return arr2.includes(item);
  });
}

// const bol = isIncludes(
//   ["banner-list", "banner-add"],
//   ["banner-list", "banner-add"]
// );
// console.log(bol);

// const roles = ['banner-list', 'banner', 'banner-add'] // ['banner-list', 'banner', 'banner-add']
// const roles = ['manager', 'manager-list', 'banner', 'banner-add'] // ['manager', 'manager-list', 'banner-add']

// 1. 获取 roles 中每一项的 children,
//    1. 能获取
//              children: ["banner-list","banner-add"]
//        1. 判断当前 children 中的每一项是否在 roles 中都有
//            1. 都有：保留
//            2. 否则：删除当前元素
//    2. 不能获取 当前元素直接保留
// const result = ["banner-list"]

// const roles = ["banner-list", "banner"];
const result = roles.filter((role) => {
  const children = getChildrenByName(routes, role);
  console.log("===", role, children);
  if (children.length) {
    return isIncludes(children, roles);
  } else {
    return true;
  }
});

console.log(result);

// every(callback)   数组每一项都要满足callback中的条件，就返回true，否则返回false
// some(callback)    数组中只要有一项满足callback中的条件，就返回true，否则返回false

// const isOK = [1, 2, -1, 3].some((item) => {
//   console.log(item);
//   return item > 0;
// });
// console.log(isOK);
